import 'package:dio/dio.dart' as dio; // 给 dio 库添加前缀
import 'package:get/get.dart';
import 'package:oli/Constant.dart';
import 'package:oli/bean/ApiResponse.dart';
import 'package:oli/router/MainRoutePath.dart';
import 'package:oli/utils/Util.dart';

class ApiService {
  // 单例模式，确保只有一个 Dio 实例
  static final dio.Dio _dio = dio.Dio(
    dio.BaseOptions(
      receiveTimeout: const Duration(milliseconds: 60000),
      connectTimeout: const Duration(milliseconds: 60000),
    ),
  );

  // 发送 GET 请求到指定的 endpoint
  static Future<ApiResponse> getRequest(String endpoint) async {
    try {
      final String token = await _getToken();
      final String url = '$BASE_URL$endpoint';
      final headers = await _buildHeaders(token);
      print('GET URL: $url');

      final dio.Response response = await _dio.get(
        url,
        options: dio.Options(headers: headers),
      );
      await _extractAndSaveToken(response.headers);
      return _handleResponse(response);
    } catch (e) {
      return _handleError(e);
    }
  }

  // 发送 POST 请求到指定的 endpoint，并附带请求体
  static Future<ApiResponse> postRequest(
    String endpoint,
    Map<String, dynamic> body,
  ) async {
    try {
      final String token = await _getToken();
      final String url = '$BASE_URL$endpoint';
      print('POST URL: $url, Body: $body');
      final headers = await _buildHeaders(token);
      final dio.Response response = await _dio.post(
        url,
        data: body,
        options: dio.Options(headers: headers),
      );
      await _extractAndSaveToken(response.headers);
      return _handleResponse(response);
    } catch (e) {
      return _handleError(e);
    }
  }

  // 提取 Cookie 并存储 token
  static Future<void> _extractAndSaveToken(dio.Headers headers) async {
    final cookies = headers['set-cookie'];
    if (cookies != null) {
      for (var cookie in cookies) {
        print('Cookie: $cookie');
        final tokenIndex = cookie.indexOf('token=');
        if (tokenIndex != -1) {
          final endIndex = cookie.indexOf(';', tokenIndex);
          final token =
              endIndex != -1
                  ? cookie.substring(tokenIndex + 6, endIndex)
                  : cookie.substring(tokenIndex + 6);
          // 保存 token
          await saveToken(token);
          print('Found token in cookie and saved: $token');
        }
      }
    }
  }

  // 构建请求头
  static Future<Map<String, String>> _buildHeaders(String? token) async {
    final headers = <String, String>{};
    if (token != null) {
      headers['Authorization'] = 'Bearer $token';
    }
    return headers;
  }

  // 处理响应并转换为 ApiResponse
  static ApiResponse _handleResponse(dio.Response response) {
    print("收到响应: ${response.statusCode} ${response.data}");
    try {
      return ApiResponse.fromJson(response.data);
    } catch (e) {
      throw Exception('无法解析响应数据: $e');
    }
  }

  // 统一处理异常
  static ApiResponse _handleError(dynamic error) {
    if (error is dio.DioException) {
      if (error.response != null) {
        return _handleResponse(error.response!);
      } else {
        toastCenter("网络请求失败: ${error.message}");
        throw Exception('网络请求失败: ${error.message}');
      }
    } else {
      toastCenter("请求失败: $error");
      throw Exception('请求失败: $error');
    }
  }

  // 获取 token，如果没有则跳转到登录页面
  static Future<String> _getToken() async {
    final token = await getToken();
    if (token.isEmpty) {
      Get.toNamed(MainRoutePath.logic);
    }
    return token;
  }
}
